package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.*;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> findMainMenu() {
        List<Menu> menuList= menuDao.findMainMenu() ;
        if(menuList!=null && menuList.size()>0){
            for (Menu menu : menuList) {
             List<Role>   roleList =  menuDao.findRoles(menu.getId());
             if(roleList!=null &&roleList.size()>0){
                 Set<Role> roleSet=new HashSet<>();
                 for (Role role : roleList) {
                     roleSet.add(role);
                 }
                 menu.setRoles(roleSet);
             }
            }
        }
        return menuList;
    }

    @Override
    public List<Menu> findChilds(String s) {
        List<Menu> menuList= menuDao.findChilds(s);
        if(menuList!=null && menuList.size()>0){
            Set<Role> set=null;
            for (Menu menu : menuList) {
                List<Role> roles = menuDao.findRoles(menu.getId());
                if(roles!=null && roles.size()>0){
                    set=new HashSet<>();
                    for (Role role : roles) {
                        set.add(role);
                    }
                }
                menu.setRoles(set);
            }
        }
        return menuList;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Menu> page=menuDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Role> findAllRole() {
        return menuDao.findAllRole();
    }

    @Override
    public List<Integer> findRolesIdByMenuId(Integer menuId) {
        return menuDao.findRolesIdByMenuId(menuId);
    }

    @Override
    public void updateRoleByMenuId(Integer menuId, Integer[] roleIds) {
        menuDao.deleteAllrole(menuId);
        if(roleIds!=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                menuDao.buildRelation(menuId,roleId);
            }
        }
    }

    @Override
    public void CreateNewMenu(Menu menu) {
        menuDao.CreateNewMenu(menu);
    }


}
